package com.zjun.demo.experimentaldemo.audio

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioDeviceInfo
import android.media.AudioManager
import androidx.core.content.ContextCompat


/**
 * 有线耳机的接入监听
 */
class HeadsetStateProvider(
    private var context: Context?,
    private var headsetIsConnected: ((Boolean)->Unit)? = null,
) {

    // The current state of wired headies; true means enabled
    private var isHeadsetPlugged = getHeadsetState()

    private var audioManager:AudioManager? = null

    // Create BroadcastReceiver to track the headset connection and disconnection events
    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            if (intent.action == AudioManager.ACTION_HEADSET_PLUG) {
                when (intent.getIntExtra("state", -1)) {
                    // 0 -- the headset is offline, 1 -- the headset is online
                    0 -> {
                        isHeadsetPlugged = false
                        headsetIsConnected?.invoke(isHeadsetPlugged)
                    }

                    1 -> {
                        isHeadsetPlugged = true
                        headsetIsConnected?.invoke(isHeadsetPlugged)
                    }
                }
            }
        }
    }

    init {
        audioManager = ContextCompat.getSystemService(context!!, AudioManager::class.java)
        val filter = IntentFilter(Intent.ACTION_HEADSET_PLUG)
        // Register our BroadcastReceiver
        context!!.registerReceiver(receiver, filter)
    }

    // The method to receive a current headset state. It's used to initialize the starting point.
    @Suppress("MemberVisibilityCanBePrivate")
    fun getHeadsetState(): Boolean {
        if(audioManager == null){
            return false
        }
        val audioDevices = audioManager!!.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
        return audioDevices.any {
            it.type == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || it.type == AudioDeviceInfo.TYPE_WIRED_HEADSET
        }
    }

    @Suppress("MemberVisibilityCanBePrivate")
    fun unregisterReceiver() {
        headsetIsConnected = null
        context!!.unregisterReceiver(receiver)
        context = null
    }

}